# -*- coding:utf-8 -*-
from framework.interface.abstract_api import AbstractApi
from marshmallow import Schema, fields, validate
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from collections import namedtuple
from flask import request

class InsertMsg(AbstractApi):
    """
    接口：InsertMsg
    文件名输入：insert_msg
    该接口访问地址为：http://10.10.31.159:9091/v1/insert-msg
    输入：
    功能：
    输出：
    """

    class PostSchema(Schema):
        msg_type = fields.Int(required=True)
        msg = fields.Str(default='')
        name = fields.Str(default='')
        room_id = fields.Int(required=True)
        weitiao = fields.Str(required=False)

    def handle_post_request(self):
        try:
            msg_type = int(request.get_json()['msg_type'])
            # post 存储会话
            if msg_type==1:
                output1 = self.insert_msg()
            else:
                output1 = self.get_msg()
            return output1
        except Exception as e:
            return f"程序异常: {str(e)}", 500

    # 存储会话
    def insert_msg(self):
        msg = request.get_json()['msg']
        weitiao = request.get_json()['weitiao']
        print("顺过来的数据",msg)
        room_id = request.get_json()['room_id']
        name = request.get_json()['name']
        data=[{'msg':msg,"room_id":room_id,"name":name,"weitiao":weitiao}]
        print(data,"测试案例")
        result = self.sql_db.insert("dailog_table",data=data,method='append',bind='ysrd_y')
        print(result,"是否存入")
        return result

    #  业务二 查询  最新会话
    def get_msg(self):
        room_id = request.get_json()['room_id']
        name = request.get_json()['name']
        sql = f"select * from dailog_table where is_deleted =0 and name!='{name}' and room_id={room_id} " \
              f"and get_people  not like  '%{name}%';"
        print(sql,"测试的数据库")
        try:
            res = self.sql_db.list(sql, bind='ysrd_y')
            # 获得那个 需要失活的id
            list_id = pd.DataFrame(res)['id'].tolist()
            list_id = str(list_id).replace("[", "(").replace("]", ")")
            # 一旦查询出来过即可让这些数据全部失活  （团队所有人都得知时候）
            self.update_msg(list_id, name, room_id)
            return res
        except:
            res =None
            return res

    #  业务二 查询  批量失活
    def update_msg(self,list_id,target_user,room_id):
        # 将更新的用户插入到这条新会话中
        excute_sql = f"""UPDATE dailog_table 
SET `get_people`=CONCAT(COALESCE(`get_people`, ''), ',{target_user}') 
WHERE id IN {list_id} and room_id = {room_id} """
        print(excute_sql,"执行数据")
        result = self.sql_db.query(excute_sql,bind='ysrd_y')
        print(result,"录入完成")
        return result